package com.lcy.demowebsocket.websocket;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lcy.demowebsocket.jms.Producer;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@Component
public class WebsocketEndPoint extends TextWebSocketHandler {

    private static Map<String, WebSocketSession> clients = new ConcurrentHashMap<>();

    private ObjectMapper objectMapper = new ObjectMapper();

    @Autowired
    private Producer producer;

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        super.handleTextMessage(session, message);
        producer.sendMessage(message.getPayload());
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        super.afterConnectionEstablished(session);
        clients.put(session.getAttributes().get("user_name").toString(),session);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        super.afterConnectionClosed(session, status);
        Map<String, Object> sessionMap = session.getAttributes();
        clients.remove((String) sessionMap.get("user_name"));
        return;
    }

    /**
     * 发送消息
     * @param message
     * @throws IOException
     */
    public void sendMessage(String  message) throws IOException {
        JSONObject object = JSONObject.fromObject(message);
        WebSocketSession receiveSession = clients.get(object.getString("receiver"));

        if(null!=receiveSession){
            JSONObject sendMsg = new JSONObject();
            sendMsg.put("message",object.getString("message"));
            sendMsg.put("sender",object.getString("sender"));
            receiveSession.sendMessage(new TextMessage(sendMsg.toString()));
        }
    }
}
